package logic

import (
	"context"
	"errors"
	"shuqi-novel/models/cache"
	"shuqi-novel/models/mysql"

	"shuqi-novel/shuqirpc/internal/svc"
	"shuqi-novel/shuqirpc/shuqirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *shuqirpc.LoginRequest) (*shuqirpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)

	if user.ID == 0 {
		user = mysql.User{
			Password: in.Password,
			Account:  in.Account,
			Address:  "请完善",
			Avatar:   "请完善",
			Name:     "请完善",
		}
		mysql.DB.Debug().Create(&user)
	}

	captchaCode, _ := cache.RDB.Get(l.ctx, "captcha"+in.Account).Result()

	if captchaCode != in.CaptchaCode {
		return nil, errors.New("图形验证码有误，请重新输入")
	}

	smsCode, _ := cache.RDB.Get(l.ctx, "sendSms"+in.Account).Result()
	if smsCode != in.SmsCode {
		return nil, errors.New("短信验证码有误，请重新输入")
	}

	if captchaCode == "" || smsCode == "" {
		return nil, errors.New("验证码为空")
	}

	if user.Password != in.Password {
		return nil, errors.New("账号或密码错误")
	}

	return &shuqirpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
